import fs from 'fs'
import { formatToHump } from './utils.js'
import { writeStoreRouter } from './router.js'
export const createStore = (tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    const folder = `${config.vendorFolder}/${tableName}`
    // verify file is exist or not
    const fileName = `${folder}/store.ts`
    if (fs.existsSync(fileName)) {
      // file is exist
      console.log(`======file is exist and ignore to created store:${tableName}=======`)
    } else {
      // file is not exist
      if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      const content = getStoreTemplate(tableName)
      fs.writeFile(fileName, content, { flag: 'a' }, (err) => {
        if (err) {
          console.log('========error======')
          throw err
        } else {
          console.log(`======succeessfully created store:${tableName}=======`)
        }
      })
    }
  })
}
const getStoreTemplate = (tableName) => {
  return `export const store = {
  state: () => ({ /** todo */ }),
  mutations: { /** todo */ },
  actions: { /** todo */ },
  getters: { /** todo */ }
}
  `
}

export const appendTopStore = (tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    const storeFile = `./${tableName}/store`
    const fileName = `${config.vendorFolder}/topStore.ts`
    const storeName = formatToHump(`store_${tableName}`)
    const importContent = `import { store as ${storeName} } from '${storeFile}'\n`
    if (fs.existsSync(fileName)) {
      // read as object and update file
      fs.readFile(fileName, 'utf8', (err, data) => {
        if (err) throw err
        if (data.indexOf(importContent) === -1) {
          const boundry = data.lastIndexOf('\n}')
          const content = importContent + data.slice(0, boundry) + `,\n\t${storeName}` + data.slice(boundry)
          writeStoreRouter(fileName, content)
        }
      })
    } else {
      // file is not exist
      if (!fs.existsSync(`${config.vendorFolder}`)) {
        fs.mkdirSync(`${config.vendorFolder}`, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      const content = `${importContent}export const topStore = {\n\t${storeName}\n}`
      writeStoreRouter(fileName, content, 'a')
    }
  })
}
